package com.example.demo.interceptor;

import com.example.demo.annotation.OnlyAdmin;
import com.example.demo.bean.SysUser;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session= request.getSession();
        String url=request.getRequestURL().toString();

        SysUser user=(SysUser)session.getAttribute("loginUser");

        if(user==null){
            response.sendRedirect("/login?returnUrl="+url);
            return false;
        }

        // 检测是否有 @OnlyAdmin 注解    把handler强转为HandlerMethod
        OnlyAdmin oa = ((HandlerMethod) handler).getMethodAnnotation(OnlyAdmin.class);
        if (oa != null) {
            // 如果不是管理员
            if (!user.getName().equals("admin")) {
                response.setContentType("text/json;charset=utf-8");
                response.getWriter().println("{\"msg\":\"你未有该权限\"}");  //输出json
                return false;
            }
        }



        return true;
    }
}
